package search.kspatial.cn.service;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import search.kspatial.cn.dao.IElementDao;
import search.kspatial.cn.pojo.Element;
import search.kspatial.cn.pojo.Images;
import search.kspatial.cn.pojo.User;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author KK
 * @create 2021/11/14 21:40
 */
public class ElementService {
    private InputStream in;
    private SqlSession session;
    private IElementDao iElementDao;

    /**
     * 初始化
     *
     * @throws IOException
     */
    public void init() throws IOException {
        //1.获取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        session = factory.openSession();
        //4.获取代理对象
        iElementDao = session.getMapper(IElementDao.class);
    }

    /**
     * 事务提交并释放资源
     *
     * @throws IOException
     */
    public void destroy() throws IOException {
        //1.提交事务
        session.commit();
        //2.释放资源
        session.close();
        in.close();
    }

    /**
     * 测试查询所有操作
     *
     * @throws IOException
     */
    public List<Element> findALLElements() throws IOException {
        init();
        //1.执行查询所有方法
        List<Element> elements = iElementDao.queryElements();
        destroy();
        return elements;
    }

    /**
     * 添加标签页
     * @param element 标签元素
     * @throws IOException
     */
    public void addElement(Element element,User user) throws IOException {
        init();
        iElementDao.addElement(element);
        iElementDao.addUser_Element(element.getEid(),user.getUid());
        destroy();
    }

    /**
     * 测试查询所有操作
     *
     * @throws IOException
     */
    public List<Images> findALLImages() throws IOException {
        init();
        //1.执行查询所有方法
        List<Images> images = iElementDao.queryImages();
        destroy();
        return images;
    }

    /**
     * 查询一个元素
     *
     * @throws IOException
     */
    public Element findElement(String title) throws IOException {
        init();
        Element element = iElementDao.queryElement(title);
        destroy();
        return element;
    }
}
